<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <form action="/" class="searchForm">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" @focus="isResult = false" background="#3195F9" />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResult" :search-text="searchText" />

    <!-- 搜索提示 -->
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch" />

    <!--搜索历史记录  -->
    <search-history v-else :search-histories.sync="searchHistories" @search="onSearch" />
  </div>
</template>

<script>
import searchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'searchIndex',
  components: {
    'search-history': searchHistory,
    'search-suggestion': searchSuggestion,
    'search-result': searchResult,
  },
  data() {
    return {
      searchText: '',
      isResult: false,
      searchHistories: getItem('TOUTIAO-SEARCH-HISTORY') || [],
    }
  },
  methods: {
    onSearch(value) {
      this.searchText = value

      // 在此将搜索记录添加到历史记录中
      const index = this.searchHistories.indexOf(value)
      if (index > -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(value)

      this.isResult = true
    },
    onCancel() {
      this.$router.back()
    },
  },
  created() {},
  watch: {
    searchHistories(value) {
      setItem('TOUTIAO-SEARCH-HISTORY',value)
    },
  },
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;

  .van-search__action {
    color: #fff;
  }

  .searchForm {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
